<?php
if (! class_exists ( "stcontroller_1_0" )) {
	class stcontroller_1_0 {
		protected static $_instance = null;
		public $view = null;

		public $config = array ();
		public $layout = "default";
		public $actionName = "index";
		public $isAjax = 0;
                public $pluginPage = "index";
                public $option = "";
                public $views = array();

		public function __construct($config) {
                        $this->setConfig($config);
                        if ( get_option('permalink_structure') != '' && !is_admin() ) {
                            $url = $_SERVER['REQUEST_URI'];

                            $home_url = get_home_url('/');

                            $parts = parse_url($home_url);
                            /*** return the host domain ***/
                            $url = $parts['scheme'].'://'.$parts['host'].$url;

                            $url = str_replace($home_url, '', $url);
                            $url_tmp = explode('/', $url);
                            foreach ($url_tmp as $value) {
                                if($value != ''){
                                    $title_tmp = $value;
                                    break;
                                }
                            }

                            if($title_tmp != '') {
                                $this->actionName = $title_tmp;
                            }
                        }
                        if (isset ( $_REQUEST ['action'] )) {
                                $this->actionName = $_REQUEST ['action'];
                        }

			$this->layout = $this->config ['default_layout'];
			$this->isAjax = false;
			$this->view = new stview_1_0 ();
			$this->view->config = $this->config;
                        if(!is_admin()){
                            $method = array($this, 'loadCss' );
                            add_action( "wp_head", $method );
                            $method = array($this, 'loadScript' );
                            add_action( "wp_print_scripts", $method );
                        }
                        $this->option = get_option($this->config['plugin_name'].'_'.$this->config['option_key'].'_settings');
		}

		public function __destruct() {

		}

		public function add_admin() {
			if ($_REQUEST ['ajax'] == 0) {
                            if(is_admin ()){
				$this->addMenuPage ();
                            }else{
                                if(isset($_REQUEST['page'])){
                                    if($_REQUEST['page'] == $this->config['plugin_name']){
                                        $this->execute ();
                                    }
                                }else{
                                    $this->execute ();
                                }
                            }
			} else {
                            if($_REQUEST['page'] == $this->config['plugin_name']){
				$this->ajax_action ();
                            }
			}
		}

		public function ajax_action() {
			$this->isAjax = true;
			$this->execute ();
			die ();
		}

		public function defaultView() {
			$this->execute ();
		}

		public static function getInstance() {
			if (null === self::$_instance) {
				self::$_instance = new self ();
			}
			return self::$_instance;
		}

		public function setConfig($config) {
			$this->config = $config;
			if ($this->actionName == "index") {
				$this->actionName = $config ['default_action'];
			}
			$this->config ['pluginDir'] = WP_PLUGIN_DIR . '/' . $config ['plugin_name'] . '/';
			$this->config ['backendCss'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/css/backend/';
			$this->config ['backendScript'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/scripts/backend/';
			$this->config ['frontendCss'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/css/frontend/';
			$this->config ['frontendScript'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/scripts/frontend/';
			$this->config ['imagesUrl'] = WP_PLUGIN_URL . '/' . $config ['plugin_name'] . '/images/';
		}

		public function execute() {
                        if( is_admin() || in_array($this->actionName, array_keys($this->views))){
                            if (is_callable ( array ($this, $this->actionName ) ) == false) {
                                    die ( "<br />Action not found: <b>Class: " . $this->config ['plugin_name'] . "Controller, Action: " . $this->actionName . "</b> in " . __FILE__ );
                            }

                            $this->registerTabMenu ();

                            $actionNameCall = $this->actionName;
                            $this->$actionNameCall ();

                            $data = $this->view->getData ();
                            $data ['current_action'] = $this->actionName;
                            $output = get_include_contents ( $this->config ['pluginDir'] . "/views/{$this->actionName}.php", $data );

                            if ($this->isAjax) {
                                    echo $output;
                            } else {
                                $data = $this->view->getData ();
                                $data ['content'] = $output;
                                $data ['config'] = $this->config;
                                $data ['tabmenus'] = $this->tabMenu;
                                $data ['current_action'] = $this->actionName;
                                $data ['option'] = $this->option;
                                if(is_admin ()){
                                    $layout = get_include_contents ( $this->config ['pluginDir'] . "/views/layout/{$this->layout}.php", $data );
                                    echo $layout;
                                }else{
                                    $this->layout = $this->views[$this->actionName];
                                    if(empty($this->layout)) $this->layout = $this->config['default_theme_layout'];
                                    $layout = get_include_contents($this->config['pluginDir'] . "/views/layout/{$this->layout}.php",$data);
                                    echo $layout;
                                    exit;
                                }
                            }
                        }
		}

		public function head() {
                    $method = array($this, 'loadSourceAdmin' );
                    add_action('admin_head', $method);
		}

                public function loadCss(){
                    //this is function import javascript
                    echo '<link href="' . $this->config ['frontendCss'] . 'style.css" rel="stylesheet" type="text/css" />' . "\n";
                    echo '<link href="' . $this->config ['frontendCss'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
                    ;
                }

                public function loadScript(){
                    //this is function import javascript
                    wp_enqueue_script('jquery');
                    wp_enqueue_script('validate', $this->config ['frontendScript'].'jquery.validate.pack.js', array( 'jquery' ) );
                    wp_enqueue_script('stcore', $this->config ['frontendScript'].'stcore.js');

                }

                public function loadSourceAdmin(){
                    //this is function import javascript
                    echo '<link href="' . $this->config ['backendCss'] . 'style.css" rel="stylesheet" type="text/css" />' . "\n";
                    echo '<link href="' . $this->config ['backendCss'] . 'custom.css" rel="stylesheet" type="text/css" />' . "\n";
                    echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.validate.pack.js"></script>';
                    echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stcore.js"></script>'
                    ;

                }

		public function customHead() {
                    $this->customAdminEnqueueScript();
                    $method = array($this, 'loadAdminCss' );
                    add_action('admin_head', $method);
                    $method = array($this, 'loadAdminScript');
                    add_action("admin_head", $method);
                }

                public function customAdminEnqueueScript() {

                }

                public function loadAdminCss(){}

                public function loadAdminScript(){}

		public function loadmodel($modelName) {
			$className = $modelName . "_model";
			$fileName = $this->config ['pluginDir'] . "models/{$modelName}.php";
			require_once $fileName;
			$obj = new $className($this->config);
			return $obj;
		}

		public function index() {
			//this is default action
		}

		protected function addMenuPage($capability = '8', $icon = '') {
                    $method = array ($this, 'defaultView' );
                    $this->pluginPage = add_menu_page ( $this->config ['page_title'], $this->config ['plugin_menu_title'], 8, $this->config ['plugin_name'], $method, $icon );
                    // load only script and css for this plugin
                    $method = array($this, 'head' );
                    add_action( "admin_print_scripts-$this->pluginPage", $method );
                    $method = array($this, 'customHead' );
                    add_action( "admin_print_scripts-$this->pluginPage", $method );
		}

		protected function setTabMenu($tabmenus) {
			foreach ( $tabmenus as $key => $value ) {
                            if(count($value) > 1){
                                foreach ( $value as $key_child => $value_child ) {
                                    $this->tabMenu [$key][$key_child] = $value_child;
                                }
                            }else
				$this->tabMenu [$key] = $value;
			}

		}

		protected function registerTabMenu() {
			if(isset($this->config['admin_tabs'])) {
				$this->setTabMenu ( $this->config['admin_tabs'] );
			}
		}

                public function activationPlugin() {
			// put your activation code here
		}

                public function deactivationPlugin() {
			// put your deactivation code here
		}

                public function getAction($action = '', $agrs = ''){
                    if($action != '' && !is_object($action)){
                        $actionNameCall = $action;
                    }
                    else{
                        $actionNameCall = $this->actionName;
                    }
                    if($agrs != '' )
                        $this->$actionNameCall ($agrs);
                    else
                        $this->$actionNameCall ();
                    $data = $this->view->getData();
                    $data ['current_action'] = $actionNameCall;
                    $output = get_include_contents ( $this->config ['pluginDir'] . "views/{$actionNameCall}.php", $data );

                    if($action != '' && !is_object($action)){
                        return $output;
                    }else{
                        echo $output;
                    }

                }

                protected function setView($views)
                {
                    foreach ($views as $view => $layout) {
                        $this->views[$view] = $layout;
                    }
                }

                protected function registerView(){

                }

                protected function updateOption($data, $message = 'Update option successful'){
                    $option = get_option($this->config['plugin_name'].'_'.$this->config['option_key'].'_settings');
                    foreach ($data as $key => $value) {
                        $option[$key] = $value;
                    }
                    update_option($this->config['plugin_name'].'_'.$this->config['option_key'].'_settings', $option);

                    if(!empty($message))
                        echo stfunctions::sendMessage(__($message, $this->config['plugin_name']));
                }

                public function ajaxPostAction(){
                    $save_type = $_POST['type'];
                    //Uploads
                    if($save_type == 'upload'){
                        $clickedID = $_POST['data']; // Acts as the name
                        $filename = $_FILES[$clickedID];
                        $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);

                        $override['test_form'] = false;
                        $override['action'] = 'wp_handle_upload';
                        $uploaded_file = wp_handle_upload($filename, $override);

                        if (!empty($uploaded_file['error'])) {
                            echo 'Upload Error: ' . $uploaded_file['error']."|*| Upload Error";
                        } else {
                            echo $uploaded_file['url']."|*|".$uploaded_file['file'];
                        } // Is the Response
                    } elseif ($save_type == 'image_remove') {
                        $file = $_POST['file']; // Acts as the name
                        unlink ($file);
                    }
                }

	}
}
?>